var height = 0, timer = null,passAccompanyList=[], currentList=[],isAdmin=location.href.includes('type');
var left = $('.left');
var right = $('.right');
var list = $('.list');
var reTel = /^\d{11}$/;
var reCard = /^\d{18}$/;
var reCar = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$/;
var currentUrl='',currentTotal=0,isLoading=false,isList=false,pageNumber= 1,currentId='2',isFirstLoad=true;
var isBig = false,fileBlob;
function $(el){
	return document.querySelector(el)
}
(function(){
	if(isAdmin){
		toggle(1,$('#mine'))
	}
	var h = window.innerHeight || document.body.clientHeight
	document.body.onscroll=function () {
		var scrollTop = document.documentElement.scrollTop||document.body.scrollTop
		if(scrollTop>(document.documentElement.scrollHeight-h)*0.8){
			if(isList&&!isLoading&&(currentList.length<currentTotal)){
				isLoading=true
				pageNumber++
				console.log(123123123)
				var loading = $('.loading')
				loading.className = 'dialog-out loading'
				ajax.get(currentUrl+pageNumber).then(res => {
					loading.className = 'dialog-out loading hidden'
					currentTotal = res.total
					currentList = currentList.concat(res.list)
					list.insertAdjacentHTML('beforeend',getList(currentId, res.list))
					isLoading=false
				})
			}
		}
	}
}())
function init(){
	var today = getToday();
	document.querySelectorAll('.date').forEach(v=>{
		v.value = today
	})
	if(!isAdmin){
		var menuList = document.querySelectorAll('.menu>div')
		menuList[0].className = menuList[1].className = 'hidden'
	}
	var str = ''
	var href = location.href
	if(isAdmin){
		str = 'employeeStudentId='+href.slice(href.indexOf('QiYeNumber')+11)
	}else{
		str = 'openId='+href.slice(href.indexOf('openId')+7)
	}
	ajax.get(`/visitorPass/list?pageNumber=1&pageSize=1&${str}`).then(res => {
		var list = res.list
		if(list.length){
			var obj = list[0].visitor
			$('input[name=visitorName]').value=obj.visitorName
			$('input[name=visitorPhoneNumber]').value=obj.visitorPhoneNumber
			$('input[name=visitorCardId]').value=obj.visitorCardId
			$('input[name=visitorCarNumber]').value=obj.visitorCarNumber
		}
	})
	$('#beforeCheck').click()
}
init()
function getToday(offset = 0) {
  var date = (new Date()).getTime()
  date = date + 86400000 * offset
  date = new Date(date)
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()
  month < 10 && (month = '0' + month)
  day < 10 && (day = '0' + day)
  return `${year}-${month}-${day}`
}
function toTop() {
	timer = setTimeout(() => {
		window.scrollTo(0, height)
	})
}
function getHeight() {
	clearTimeout(timer);
	height = document.documentElement.scrollTop || document.body.scrollTop
}
function submit() {
	if(!$('.head-img').value){
		return toast('请选择照片')
	}
	var form = new FormData($('#form'))
	if(!form.get('employeeName')){
		return toast('请输入被访人姓名')
	}
	if(!reTel.test(form.get('employeePhoneNumber'))){
		return toast('被访人电话输入错误')
	}
	if(!form.get('visitorName')){
		return toast('请输入访客姓名')
	}
	if(!reTel.test(form.get('visitorPhoneNumber'))){
		return toast('访客电话输入错误')
	}
	if(!reCard.test(form.get('visitorCardId'))){
		return toast('身份证号码输入错误')
	}
	if(form.get('visitorCarNumber')&&!reCar.test(form.get('visitorCarNumber'))){
		return toast('车牌号格式错误')
	}
	if(form.get('isAccompany')==='1'&&!form.get('accompanyName')){
		return toast('请输入随行人姓名')
	}
	if(form.get('isAccompany')==='1'&&!reTel.test(form.get('accompanyPhoneNumber'))){
		return toast('随行人电话输入错误')
	}
	if(form.get('isAccompany')==='1'&&!reCard.test(form.get('accompanyCardId'))){
		return toast('随行人身份证输入错误')
	}
	if(form.get('isAccompany')==='1'){
		passAccompanyList.push({
			accompanyName: form.get('accompanyName'),
			accompanyPhoneNumber: form.get('accompanyPhoneNumber'),
			accompanyCardId: form.get('accompanyCardId')
		})
	}
	if(!form.get('date')){
		return toast('请输入预约到达日期')
	}
	if(!form.get('time')){
		return toast('请输入预约到达时间')
	}
	if(!form.get('leaveDate')){
		return toast('请输入预约离开日期')
	}
	if(!form.get('leaveTime')){
		return toast('请输入预约离开时间')
	}
	var time = (new Date(`${form.get('date')} ${form.get('time')}`)).getTime()
	var time1 = (new Date(`${form.get('leaveDate')} ${form.get('leaveTime')}`)).getTime()
	if(time>time1){
		return toast('预约到达时间不能早于离开时间')
	}
	if(isBig){
		form.append('photo',fileBlob)
	}else{
		form.append('photo',$('.head-img').files[0])
	}
	form.append('passAccompanieString',JSON.stringify(passAccompanyList))
	form.append('visitorGender','0')
	form.append('visitorNation','汉')
	form.set('reason', ['亲友','会见','商务','其它'][form.get('reason')])
	form.set('arriveTime', `${form.get('date')} ${form.get('time')}:00`)
	form.set('leaveTime', `${form.get('leaveDate')} ${form.get('leaveTime')}:00`)
	//预约方式
	form.append('bookingType','1')
	form.append('visitorStatus','0')
	//app预约
	form.append('reserveType','1')
	if(!isAdmin){
		var href = location.href
		form.append('openId',href.slice(href.indexOf('openId')+7))
	}
	if(!form.get('remark')){
		form.set('remark','无')
	}
	var loading = $('.loading')
	loading.className = 'dialog-out loading'
	ajax.post('/visitorPass/addVisitor', form, false).then(res=>{
		loading.className = 'dialog-out loading hidden'
		if(res.code === 'success'){
			$('#form').reset()
			var headImg = $('#headImg')
			window.URL.revokeObjectURL(headImg.src)
			headImg.src = "img/cicle.png"
			init()
			passAccompanyList = []
			toggle(1,$('#mine'))
			$('.head-img').value = ''
			$('.add-person').innerHTML = '<span onclick="addPeople()">+</span>'
			$('.accompany').className = 'accompany hidden'
		}else{
			passAccompanyList.pop()
		}
		var str = res.msg
		var index = str.indexOf('error')
		if(index!==-1){
			str = str.slice(0, index-2)
		}
		toast(str)
	})
}
function getImage(){
	var target = event.target
	var file = event.target.files[0];
	var headImg = $('#headImg')
	if(headImg.src!=="img/cicle.png"){
		window.URL.revokeObjectURL(headImg.src)
	}
	if(file){
		headImg.src = window.URL.createObjectURL(file)
		if(file.size>2000000){
			isBig=true
			setTimeout(()=>{
				var percent = headImg.height/headImg.width
				var canvas=document.createElement('canvas')
				canvas.width = 300
				canvas.height = percent*300|0
				canvas.getContext('2d').drawImage(headImg, 0, 0, canvas.width, canvas.height)
				canvas.toBlob(v=>{
					fileBlob=v
				})
			},2000)
		}else{
			isBig=false
		}
	}else{
		headImg.src = "img/cicle.png"
	}
}
function toggle(type,target){
	if (target.className === 'is-active') return
	isList = !!type
	if (type) {
		left.className = 'left hidden'
		right.className = 'right'
		var sibling = target.previousElementSibling
		sibling.className = ''
		sibling.firstElementChild.className = "iconfont iconshouye2"
		target.className = 'is-active'
		target.firstElementChild.className = "iconfont iconwodedangxuan"
	} else {
		left.className = 'left'
		right.className = 'right hidden'
		var sibling = target.nextElementSibling
		sibling.className = ''
		sibling.firstElementChild.className = "iconfont iconwode"
		target.className = 'is-active'
		target.firstElementChild.className = "iconfont iconshouye1"
	}
	window.scrollTo(0, 0)
}
function changeType(){
	var target = event.target
	var id = target.getAttribute('data-id')
	if (!id) return
	$('.m-active').className = ''
	target.className = 'm-active'
	var status = ['','-4','0','1','4'][id]
	var str = ''
	var href = location.href
	if(isAdmin){
		str = 'employeeStudentId='+href.slice(href.indexOf('QiYeNumber')+11)
		var index = href.indexOf('type')
		var type = href.slice(index+5,index+6)
		if(status==='0'&&type==='2'){
			status = '5'
		}else if(status==='0'&&type==='3'){
			status = '6'
		}else if(status==='1'&&type==='1'){
			status = '-2'
		}else if(status==='1'&&type==='2'){
			status = '-3'
		}
	}else{
		str = 'openId='+href.slice(href.indexOf('openId')+7)
		if(status==='0'){
			status='-1'
		}
	}
	var url = `/visitorPass/list?pageSize=10&visitorStatus=${status}&${str}&pageNumber=`
	currentUrl = url
	currentId = id
	pageNumber= 1
	var loading = $('.loading')
	if(!isFirstLoad){
		loading.className = 'dialog-out loading'
	}else{
		isFirstLoad=false
	}
	ajax.get(url+'1').then(res => {
		loading.className = 'dialog-out loading hidden'
		currentTotal = res.total
		currentList = res.list
		list.className = currentList.length ? 'list' : 'list back'
		list.innerHTML = currentList.length ? getList(id, currentList):''
	})
}
function getList(type, list){
	var str = '';
	var num = (pageNumber-1)*10
	list.forEach((v,index) => {
		str += `<div class="item" onclick="openDialog(${num+index})">
			<div class="img-box"><img src="${baseurl+'/photo/'+v.visitor.facePhoto}" alt=""></div>
			<div class="detail">
				<div>来访人：${v.visitor.visitorName}</div>
				<div>受访人：${v.visitor.employeeName}</div>
				<div>来访原因：${v.visitor.reason}</div>
				<div>预约时间：<span class="blue">${v.visitor.arriveTime}</span></div>
				${getDom(type, v.visitor)}
			</div>
		</div>`
	});
	return str
}
function getDom(type, data){
	if(type==='2'&&!isAdmin){
		return ''
	}
	var status = ['待审核', '已通过', '已签到', '已签离', '已拒绝', '待审核', '待审核']
	var color = ['blue', 'green', 'green', 'green', 'red', 'blue', 'blue']
	var ls = [
		`<div>审批状态：<span class="${color[data.visitorStatus]}">${status[data.visitorStatus]}</span></div>`,
		`<div>到访时间：<span class="green">${data.signIn}</span></div>`,
		`<div><div class="agree" onclick="agree(${data.id})">同意</div><div onclick="agree(${data.id},1)" class="disagree">拒绝</div></div>`,
		`<div>审批时间：<span class="green">${getTime(data.modifyDate)}</span></div>`,
		`<div>审批时间：<span class="red">${getTime(data.modifyDate)}</span></div>`
	]
	return ls[type]
}
function getTime(time) {
  if (!time) return ''
  var date = new Date(time)
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()
  var h = date.getHours()
  var m = date.getMinutes()
  var s = date.getSeconds()
  month < 10 && (month = '0' + month)
  day < 10 && (day = '0' + day)
  h < 10 && (h = '0' + h)
  m < 10 && (m = '0' + m)
  s < 10 && (s = '0' + s)
  return `${year}-${month}-${day} ${h}:${m}:${s}`
}
function agree(id,flag){
	event.stopPropagation()
	var href = location.href
	var index = href.indexOf('type')
	var type = href.slice(index+5,index+6)
	var loading = $('.loading')
	loading.className = 'dialog-out loading'
	ajax.get(`/visitorApproval/approveLevel${type}?visitorStatus=${flag?'4':'1'}&visitorId=${id}`).then(res=>{
		toast(res.msg)
		loading.className = 'dialog-out loading hidden'
		$('#beforeCheck').click()
	})
}
function addPeople(){
	var name = $('#name').value
	if(!name){
		return toast('请输入姓名')
	}
	if(!reTel.test($('#tel').value)){
		return toast('手机号错误')
	}
	if(!reCard.test($('#identity').value)){
		return toast('身份证号错误')
	}
	passAccompanyList.push({
		accompanyName: name,
		accompanyPhoneNumber: $('#tel').value,
		accompanyCardId: $('#identity').value
	})
	$('#name').value = $('#tel').value = $('#identity').value = ''
	event.target.parentElement.innerHTML = `<span>${name}</span>` + event.target.parentElement.innerHTML
}
function toast(msg){
	var vanToast = $('.van-toast')
	vanToast.innerText = msg
	vanToast.className = 'van-toast fade-in-active'
	setTimeout(()=>{
		vanToast.className = 'van-toast fade-out-active'
	}, 2000)
	setTimeout(()=>{
		vanToast.className = 'van-toast hidden'
	}, 2290)
}
function openDialog(index){
	var dialog = $('.dialog-out')
	dialog.className = 'dialog-out fade-in-active'
	var obj = currentList[index]
	var visitor = obj.visitor
	var html = `<label>
		<img class="icon" src="img/name01.png" alt="">
		<div>被访人姓名</div>
		<span>${visitor.employeeName}</span>
	</label>
	<label>
		<img class="icon" src="img/tel01.png" alt="">
		<div>被访人电话</div>
		<span>${visitor.employeePhoneNumber}</span>
	</label>
	<label>
		<img class="icon" src="img/name02.png" alt="">
		<div>访客姓名</div>
		<span>${visitor.visitorName}</span>
	</label>
	<label>
		<img class="icon" src="img/tel02.png" alt="">
		<div>访客电话</div>
		<span>${visitor.visitorPhoneNumber}</span>
	</label>
	<label>
		<img class="icon" src="img/id01.png" alt="">
		<div>身份证号码</div>
		<span>${visitor.visitorCardId}</span>
	</label>
	<label>
		<img class="icon" src="img/car.png" alt="">
		<div>访客车牌</div>
		<span>${visitor.visitorCarNumber}</span>
	</label>
	<label>
		<img class="icon" src="img/go.png" alt="">
		<div>是否有随行</div>
		<span>${obj.passAccompanyList.length?'是':'否'}</span>
	</label>`
	if(obj.passAccompanyList.length){
		obj.passAccompanyList.forEach(v=>{
			html += `<label>
				<img class="icon" src="img/name03.png" alt="">
				<div>随行人姓名</div>
				<span>${v.accompanyName}</span>
			</label>
			<label>
				<img class="icon" src="img/tel03.png" alt="">
				<div>随行人电话</div>
				<span>${v.accompanyPhoneNumber}</span>
			</label>
			<label>
				<img class="icon" src="img/id02.png" alt="">
				<div>身份证号码</div>
				<span>${v.accompanyCardId}</span>
			</label>`
		})
	}
	html += `<label>
		<img class="icon" src="img/reason.png" alt="">
		<div>到访事宜</div>
		<span>${visitor.reason}</span>
	</label>
	<label>
		<img class="icon" src="img/arrive.png" alt="">
		<div>预约到达时间</div>
		<span>${visitor.arriveTime}</span>
	</label>
	<label>
		<img class="icon" src="img/leave.png" alt="">
		<div>预约离开时间</div>
		<span>${visitor.leaveTime}</span>
	</label>
	<label>
		<img class="icon" src="img/remarks.png" alt="">
		<div>备注信息</div>
		<span>${visitor.remark}</span>
	</label>`
	$('.dialog-body').innerHTML = html
}
function closeDialog(){
	var dialog = $('.dialog-out')
	dialog.className = 'dialog-out fade-out-active'
	setTimeout(()=>{
		dialog.className = 'dialog-out hidden'
	}, 290)
}
function changeAccompany(self){
	$('.accompany').className = self.value==='0' ? 'accompany hidden' : 'accompany'
	if(self.value==='0'){
		passAccompanyList=[];
		$('.add-person').innerHTML = '<span onclick="addPeople()">+</span>'
	}
}